<template>
  <div class="app-container" style="height: 100%;">
    <el-card>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" label-position="top">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="实践课程" prop="practiceType">
              <el-select v-model="form.practiceType" placeholder="请选择实践课程" clearable style="width:100%">
                <el-option v-for="item in practiceTypeList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="题目类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择题目类型" clearable style="width:100%" @change="changeType">
                <el-option v-for="item in taskStatusList" :key="item.id" :label="item.type" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="题干" prop="questionContent">
              <RichText v-model="form.questionContent" :min-height="300" @update-value="updateValue"></RichText>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选项" class="radioStyle">
              <div v-for="(item, index) in optionList" :key="item.name" class="bankLabelStyle">
                <el-checkbox v-model="item.answer" :label="item.name" style="display: block;">
                </el-checkbox>
                <el-button size="small"> {{ item.name }} </el-button>
                <Editor style="flex: 1" v-model="item.content"></Editor>
                <el-button size="mini"> 富文本 </el-button>
                <el-button type="text" icon="el-icon-delete" @click="deleOption(index)" v-if="form.type != 2"></el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.type != 2">
            <el-button size="mini" @click="addOption"> 新增选项 </el-button>
          </el-col>
          <el-col :span="24">
             <!-- prop="answerAnalysis" -->
            <el-form-item label="答案解析">
              <RichText v-model="form.answerAnalysis" :min-height="300" @update-value="updateAnalysis"></RichText>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div style="text-align: center; margin-top: 10px;">
              <el-button @click="returnBtn">取 消</el-button>
              <el-button type="primary" @click="submitForm('保存')">保 存</el-button>
              <el-button type="success" @click="submitForm('创建')" v-if="!this.bankId">保存并创建下一题</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from "vuex"
import { typeCongfigList } from "@/api/semesManage";
import { addPaper, updatePaper, detailPaper } from "@/api/paperInterlocu/paper";
export default {
  name: "addBank",
  data() {
    return {
      form: {
        practiceType: '',
        type: 1,
        questionContent: '',
        answerAnalysis: '',
        questionBankOptionList: []
      },
      taskStatusList: [{ id: 1, type: '单选题' }, { id: 2, type: '判断题' }, { id: 3, type: '多选题' }], // 任务状态
      practiceTypeList: [], // 实践课程
      allLetters: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''), // 所有字母
      optionList: [
        { name: 'A', answer: '', content: '', sort: 1, },
        { name: 'B', answer: '', content: '', sort: 2, },
        { name: 'C', answer: '', content: '', sort: 3, },
        { name: 'D', answer: '', content: '', sort: 4, },
      ],
      // 表单校验
      rules: {
        practiceType: [
          { required: true, message: "请选择实践课程", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择任务类型", trigger: "change" },
        ],
        questionContent: [
          { required: true, message: "题干不得为空", trigger: "blur" },
        ],
        // answerAnalysis: [
        //   { required: true, message: "答案解析不得为空", trigger: "blur" },
        // ],
      },
      // 试题id
      bankId: null
    };
  },
  watch: {},
  created() {
    // const permissList = sessionStorage.getItem('practiceTypes').split(',');
    // const typeMap = {
    //   1: { type: '劳动教育', id: 1 },
    //   2: { type: '职业素养', id: 2 },
    //   3: { type: '应急安全', id: 3 },
    //   4: { type: '思政实践', id: 4 },
    //   5: { type: '创新创业', id: 5 }
    // };

    // permissList.forEach(v => {
    //   if (typeMap[v]) {
    //     this.practiceTypeList.push(typeMap[v]);
    //   }
    // });

    this.getTypeCongfigList();
    if (this.$route.query.id) {
      this.bankId = this.$route.query.id;
      this.getBankDetail();
    }
    const routeIndex = this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path);
    this.$store.state.tagsView.visitedViews[routeIndex].title = this.$route.query.id ? '编辑试题' : '新增试题';
    this.$store.state.tagsView.visitedViews[routeIndex].meta.title = this.$route.query.id ? '编辑试题' : '新增试题';
  },

  computed: {
    ...mapGetters([
      "visitedViews",
    ])
  },
  beforeRouteEnter(form, to, next) {
    form.meta.title = form.meta.title;
    next();
  },
  methods: {
    getTypeCongfigList() {
      typeCongfigList({
        pageNum: 1,
        pageSize: 50,
      }).then(res => {
        this.practiceTypeList = res.rows;
      });
    },
    // 编辑获取详情
    getBankDetail() {
      detailPaper(this.bankId).then(res => {
        if (res.code == 200) {
          this.form = res.data;
          this.optionList = [];
          this.form.questionBankOptionList.forEach(item => {
            this.optionList.push({ ...item, answer: item.answer == 1 ? true : '' });
          });
        }
      })
    },
    // 新增选项
    addOption() {
      // 如果还有字母未添加
      if (this.optionList.length < this.allLetters.length) {
        // 将下一个字母添加到字母数组中
        this.optionList.push({ name: `${this.allLetters[this.optionList.length]}`, answer: '', content: '', sort: this.optionList.length + 1 });
      } else {
        this.$modal.msgError('最多只能26个选项!')
      }
    },
    // 删除选项
    deleOption(index) {
      if (this.optionList.length < 3) return this.$modal.msgError('最少需要两个选项!');
      this.optionList.splice(index, 1);
      // 更新后续选项的，使其变成前一个字母
      if (index === 0) {
        this.optionList.forEach((item, i) => {
          const nextLabel = String.fromCharCode(this.optionList[i].name.charCodeAt(0) - 1); // 字母转换
          this.optionList[i].name = nextLabel;
          this.optionList[i].sort = this.optionList[i].sort - 1;
        })
        return;
      }
      for (let i = index; i < this.optionList.length; i++) {
        const nextLabel = String.fromCharCode(this.optionList[i - 1].name.charCodeAt(0) + 1); // 字母转换
        this.optionList[i].name = nextLabel;
        this.optionList[i].sort = this.optionList[i].sort - 1;
      }
    },
    updateValue(row) {
      this.form.questionContent = row;
    },
    updateAnalysis(row) {
      this.form.answerAnalysis = row;
    },
    changeType(type) {
      if (type == 2) {
        this.optionList = [
          { name: 'A', answer: '', content: '', sort: 1, },
          { name: 'B', answer: '', content: '', sort: 2, },
        ]
      }
      if (this.optionList.length == 2 && type != 2) {
        this.optionList = [
          { name: 'A', answer: '', content: '', sort: 1, },
          { name: 'B', answer: '', content: '', sort: 2, },
          { name: 'C', answer: '', content: '', sort: 3, },
          { name: 'D', answer: '', content: '', sort: 4, },
        ]
      }
    },
    // 返 回
    returnBtn() {
      let path = this.$route.path;
      const routrIndex = this.$store.state.tagsView.visitedViews.findIndex(item => item.path === path);
      this.$store.state.tagsView.visitedViews.splice(routrIndex, 1);
      this.$router.go(-1);
    },
    // 保 存
    submitForm(type) {
      if (this.optionList.find(v => v.content == '' || v.content == '<p><br></p>')) return this.$modal.msgError('选项内容不得为空,请检查!');
      let answerNum = 0;
      if (this.form.type == 3) {
        this.optionList.forEach(v => {
          if (v.answer != '') {
            answerNum++;
          }
        })
        if (answerNum < 2) return this.$modal.msgError('多选题正确答案至少设置两项!');
      } else {
        if (!this.optionList.find(v => v.answer != '')) return this.$modal.msgError('单选题与判断题, 正确答案至少设置一项!');

        this.optionList.forEach(v => {
          if (v.answer != '') {
            answerNum++;
          }
        })
        if (answerNum > 1) return this.$modal.msgError('单选题与判断题, 正确答案最多设置一项!');
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.questionContent == '<p><br></p>') return this.$modal.msgWarning("题干不得为空!");
          // if (this.form.answerAnalysis == '<p><br></p>') return this.$modal.msgWarning("答案解析不得为空");
          this.form.questionBankOptionList = [];
          this.optionList.forEach(item => {
            this.form.questionBankOptionList.push({ ...item, answer: item.answer ? 1 : 0 })
          })
          if (this.form.id) {
            updatePaper(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.returnBtn();
            });
          } else {
            addPaper(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              if (type == "保存") {
                this.returnBtn();
              } else {
                this.form = {
                  practiceType: '',
                  type: 1,
                  questionContent: '',
                  answerAnalysis: '',
                  questionBankOptionList: []
                };
                this.optionList = [
                  { name: 'A', answer: '', content: '', sort: 1, },
                  { name: 'B', answer: '', content: '', sort: 2, },
                  { name: 'C', answer: '', content: '', sort: 3, },
                  { name: 'D', answer: '', content: '', sort: 4, },
                ];
              }
            });
          }
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-form-item__label {
  padding: 0;
}

.bankLabelStyle {
  display: flex;
  margin: 8px;
}

.radioStyle {
  button {
    display: block;
    margin: 5px;
  }

  ::v-deep .el-checkbox__label {
    display: none !important;
  }

  ::v-deep .el-form-item__content {
    .ql-toolbar {
      display: none;
    }

    .ql-snow {
      border-top: 1px solid #ccc;
    }
  }
}


::v-deep .el-radio__original {
  display: none !important;
  /* 隐藏原生 radio 输入，但仍然允许交互 */
}

::v-deep.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
  box-shadow: none !important;
}
</style>
